// original code from 
// http://interface.khm.de/index.php/lab/experiments/infrared-thermometer-mlx90614/
// 
#include <i2cmaster.h>

char st1[30];

void setup()
{
  Serial.begin(9600);
  Serial.println("Melexis MLX90614 temperature Sensor");

  pinMode(13,OUTPUT);
  for ( int i = 0 ; i < 10 ; i++){

    digitalWrite(13,LOW);
    delay(100);
    digitalWrite(13,LOW);
    delay(100);
  }

  //enable internal pullup resistors on i2c ports
  // PORTC = (1 << PORTC4) | (1 << PORTC5);  

}
void loop()
{

  long int tpl;

  digitalWrite(13,HIGH);
  tpl=readMLXtemperature(0); // read sensor object temperature
  tpl = tpl *10;
  tpl = tpl / 5;
  tpl=tpl-27315;
  sprintf(st1,"object temperature: %03li.%li",tpl/100, abs(tpl %100) );
  Serial.print(st1);
  Serial.print("   ");

  /*
  tpl=readMLXtemperature(1); // read sensor ambient temperature
   tpl = tpl *10;
   tpl = tpl / 5;
   tpl=tpl-27315;
   sprintf(st1,"ambient temp: %03li.%li",tpl/100, tpl %100 );
   Serial.print(st1);
   Serial.print("   ");
   */
  Serial.println("");
  digitalWrite(13,LOW);
  delay(100);

}
//****************************************************************
// read MLX90614 i2c ambient or object temperature
long int readMLXtemperature(int TaTo) {
  long int lii;
  int dlsb,dmsb,pec;
  int dev = 0x5A<<1;

  i2c_init();
  // set device address and write mode
  i2c_start_wait(dev+I2C_WRITE);

  // or command read object or ambient temperature
  if (TaTo) i2c_write(0x06); 
  else i2c_write(0x07);                

  i2c_rep_start(dev+I2C_READ);  // set device address and read mode
  dlsb = i2c_readAck();       // read data lsb
  dmsb = i2c_readAck();      // read data msb
  pec = i2c_readNak();
  i2c_stop();

  lii=dmsb*0x100+dlsb;
  return(lii);
}

